/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package researchgrants.parts.GrantRequest.reminder;

import java.awt.Window;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import researchgrants.parts.GrantRequest.GrantRequest;
import researchgrants.parts.LoggedData.LoggedData;
import researchgrants.parts.LoggedData.LoggedDataOutSerializable;
import researchgrants.parts.date.DateForDb;
import researchgrants.parts.date.LoggedDate;
import researchgrants.parts.db.Db;

/**
 * Represent a Reminder. Each reminder has a date (to remind) and a comment.
 * 
 * The class is LoggedDataOutSerializable to allow it to be saved implicitly through panels
 * This object is a field within a GrantRequest
 * @author DOStudent1
 */
public class Reminder implements LoggedDataOutSerializable{

    // Creates a new Reminder
    static Reminder inputNew(Window parent, GrantRequest grantRequest) {
        // initializes an unbound Reminder View - to input the new Reminder
        ReminderView viewNew = new ReminderView(parent, grantRequest);
        // Returns the newly created Reminder
        Reminder newReminder=viewNew.getReminder();
        if (newReminder!=null) {
            grantRequest.saveNewReminder(newReminder);
        }
        return (newReminder);
    }

    // Returns an existing Reminder
    static public Reminder getById(int id) {
        return(new Reminder(id));
    }

    // the identification field of the Reminder
    private int id;
    
    // The elements of the Reminder
    private LoggedData date;
    private LoggedData notes;
    
    // private constructor
    private Reminder(int id) {
        this.id=id;
        syncDataFromDb();
    }

    // populate the fields from the database
    private void syncDataFromDb() {
        try {
            Connection conn = Db.openDbConnection();
            PreparedStatement prepareStatement = Db.createPreparedStatement(conn, "SELECT DateRef, NotesRef FROM tblReminders WHERE ReminderID=?");
            prepareStatement.setInt(1, id);
            ResultSet resultSet = prepareStatement.executeQuery();
            Db.moveToFirstLine(resultSet);

            date=LoggedData.getByID((Integer) Db.getColumn(resultSet, 1));
            notes=LoggedData.getByID((Integer) Db.getColumn(resultSet, 2));
                    
            resultSet.close();
            prepareStatement.close();
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(Reminder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Reminder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //////////////////////////////////////
    // Retreives the elements' values
    //////////////////////////////////////

    public int getId() {
       return(id);
    }

    public Date getCurrentDate() {
        final String value = date.value();
        if (value.equals(""))  {
            return(null);
        } else {
            return(LoggedDate.fromLoggedData(value));
        }
    }

    public String getCurrentNotes() {
        return(notes.value());
    }

    //////////////////////////////////////
    // Retreives the raw elements
    // Used to populate the panels to display the Reminder in ReminderView
    //////////////////////////////////////

    LoggedData getLoggedDataDate() {
        return(date);
    }

    LoggedData getLoggedDataNotes() {
        return(notes);
    }

    
    
    // Used to summarize the Reminder
    public String getDescription() {
        Date currDate=getCurrentDate();
        
        return ("Reminding on " + DateForDb.fromDate(currDate).toDisplayString());
    }
    
    // Shows the Reminder
    void show(Window parent) {
        new ReminderView(parent, this);
    }
 
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    // Support saving and loading a AngecyContact through its panels: LoggedDataPanelsListExpnesePurpose
    ///////////////////////////////////////////////////////////////////////////////////////////////////////

    @Override
    public String toLoggedData() {
        return(Integer.toString(id));
    }

    public static Reminder fromLoggedData(String loggedData) {
        return(Reminder.getById(Integer.parseInt(loggedData)));
    }

    /**
     * Cancels the reminder.
     * Leaves the <code>Reminder</code> unconnected to the <code>GrantRequest</code>.
     * By looking at previous <code>LoggedData</code> of the reference, old <code>Reminder</code>s can be retreiven.
     * @param grantRequest  the associated <code>GrantRequest</code>. If not the actual owner <code>GrantRequest</code> is provided, a run time error is raised.
     */
    public void cancelReminder(GrantRequest grantRequest) {
        if (!grantRequest.getCurrentReminder().equals(this)) {
            throw new RuntimeException("The given GrantRequest is not the owner of the reminder");
        }
        
        grantRequest.cancelReminder();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Reminder other = (Reminder) obj;
        if (this.id != other.id) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 23 * hash + this.id;
        return hash;
    }
    
}
